//
//  HomeViewController.swift
//  SwiftWB
//
//  Created by 钟清 on 17/3/24.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage

class HomeViewController: BaseViewController {
    /* 保存所有微博数据的变量 */
    var statusListModel: StatusListModel = StatusListModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        /// 1,设置游客访问视图
        if !isLogin { // 未登陆
            visitorView?.setUpVisitorInfo(nil, text: "关注一些人，回来看看有惊喜哈")
            return
        }
        
        /// 2,设置登录导航条
        setUpNav()
        
        /// 3,注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeViewController.titleChange), name: SWPresentationManagerDidPresented, object: presentManager)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeViewController.titleChange), name: SWPresentationManagerDidDismissed, object: presentManager)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeViewController.showPictureBrowser(_:)), name: SWPictureBrowserController, object: nil)
        
        /* 4,下载数据 */
        loadData()
        // tableView.estimatedRowHeight = 200 // 先给一个预定值，可适当提高效率
        // tableView.rowHeight = UITableViewAutomaticDimension
        
        /* 5,取消分割条 */
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        /* 6,初始化下拉刷新 */
        refreshControl = SWRefreshControl()
        refreshControl?.addTarget(self, action: #selector(HomeViewController.loadData), forControlEvents: UIControlEvents.ValueChanged)
        refreshControl?.beginRefreshing()
        /* 7, 添加刷新提醒 */
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
    }
    deinit
    {
        /// 移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 内部控制方法
    /* 下载数据 */
    @objc private func loadData() {
            statusListModel.loadData(lastStatus) { (models, error) in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("获取微博数据失败")
                    SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
                    return
                }
                /*  关闭下载提示视图 */
                self.refreshControl?.endRefreshing()
                /* 刷新提示 */
                self.showRefreshTip(models!.count)
                /* 刷新表格 */
                self.tableView.reloadData()
                /* 标记重置 */
                self.lastStatus = false
        }
    }
    /* 刷新提示 */
    private func showRefreshTip(count: Int) {
        tipLabel.text = (count == 0) ? "没有更多数据" : "刷新到了\(count)条数据"
        UIView.animateWithDuration(0.75, animations: {
            self.tipLabel.hidden = false
            self.tipLabel.transform = CGAffineTransformMakeTranslation(0, 44)
            }) { (_) in
                UIView.animateWithDuration(0.75, delay: 1.5, options: UIViewAnimationOptions(rawValue:0), animations: {
                    self.tipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) in
                        self.tipLabel.hidden = true
                })
        }
    }
    /* 展示图片浏览器 */
    @objc private func showPictureBrowser(notice: NSNotification) {
        /* 安全校验 */
        guard let pictures = notice.userInfo!["bmiddle_pic"] as? [NSURL] else {
            SVProgressHUD.showErrorWithStatus("没有图片")
            return
        }
        guard let index = notice.userInfo!["indexPath"] as? NSIndexPath else {
            SVProgressHUD.showErrorWithStatus("没有索引")
            return
        }
        guard let pictureView = notice.object as? SWPictureView else {
            return
        }
        /* 弹出图片浏览器 */
        let pictureVc = PictureBrowserViewController(bmiddle_pic: pictures, indexPath: index)
        /* 转场动画代理 */
        pictureVc.transitioningDelegate = browserPresentationManager
        /* 转场动画样式 */
        pictureVc.modalPresentationStyle = UIModalPresentationStyle.Custom
        /* 转场动画需要的数据 */
        browserPresentationManager.setDefaultInfo(index, browserDelegate: pictureView)
        presentViewController(pictureVc, animated: true, completion: nil)
        
    }
    
    /* 设置导航条 */
    private func setUpNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: #selector(HomeViewController.leftBarButtonClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(HomeViewController.rightBarButtonClick))
        navigationItem.titleView = titleButton
    }
    
    @objc private func leftBarButtonClick() {
        ZQLog("")
    }
    /* 二维码打开 */
    @objc private func rightBarButtonClick() {
        guard let qrVC = R.storyboard.qRCode.initialViewController() else {
            ZQLog("获得QRCode.storyboard的View")
            return
        }
        presentViewController(qrVC, animated: true, completion: nil)
    }
    /* 标题切换 */
    @objc private func titleChange() {
        titleButton.selected = !titleButton.selected
    }
    /* 标题菜单显示 */
    @objc private func titleButtonClick(btn: TitleButton) {
        /// 显示菜单
        guard let menuView = R.storyboard.popover.initialViewController() else {
            ZQLog("无法获得Popover.storyboard")
            return
        }
        menuView.transitioningDelegate = presentManager
        menuView.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(menuView, animated: true, completion: nil)
    }
    
    // MARK: - Lazy
    /* 标题菜单 */
    private lazy var presentManager : SWPresentationManager = {
        let manager = SWPresentationManager()
        manager.presentFrame = CGRect(x: 65, y: 55, width: 200, height: 200)
        return manager
    }()
    /* 标题按钮 */
    private lazy var titleButton : TitleButton = {
        let btn = TitleButton()
        let title = UserAccount.loadUserAccount()?.screen_name
        btn.setTitle(title, forState: UIControlState.Normal)
        btn.addTarget(self, action: #selector(HomeViewController.titleButtonClick(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    /* 刷新提醒视图 */
    private var tipLabel: UILabel = {
        let label = UILabel()
        label.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 44)
        label.text = "没有更多数据了"
        label.textAlignment = NSTextAlignment.Center
        label.textColor = UIColor.whiteColor()
        label.backgroundColor = UIColor.orangeColor()
        label.hidden = true
        return label
    }()
    /* 缓存行高 */
    private var rowHeightCaches = [String : CGFloat]()
    /* 标记：最后一条微博 */
    private var lastStatus = false
    /* 转场动画管理者 */
    private lazy var browserPresentationManager: PictureBrowserPresentationController = PictureBrowserPresentationController()
}

extension HomeViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListModel.statuses?.count ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        /* 原创和转发的cell需要区分选取 */
        let viewModel = statusListModel.statuses![indexPath.row]
        let identifier = (viewModel.status.retweeted_status != nil) ? "forwardCell" : "homeCell"
        let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! HomeTableViewCell
        cell.viewModel = viewModel
        /* 最后一条微博微博 */
        if indexPath.row == statusListModel.statuses!.count - 1 {
            lastStatus = true
            loadData()
        }
        return cell
    }
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        /* 原创和转发的cell需要区分选取 */
        let viewModel = statusListModel.statuses![indexPath.row]
        let identifier = (viewModel.status.retweeted_status != nil) ? "forwardCell" : "homeCell"
        guard let rowHeight = rowHeightCaches[viewModel.status.idstr ?? "-1"] else {
            // ZQLog("计算行高")
            let cell = tableView.dequeueReusableCellWithIdentifier(identifier) as! HomeTableViewCell
            let temp = cell.calculateRowHeight(viewModel)
            rowHeightCaches[viewModel.status.idstr ?? "-1"] = temp
            return temp
        }
        return rowHeight
    }
    override func didReceiveMemoryWarning() {
        rowHeightCaches.removeAll()
    }
}

